package com.amway.qy.core.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amway.qy.core.constants.QyWechatUrls;
import com.amway.qy.core.service.QyAccessTokenService;
import com.amway.qy.core.service.QyExchangeIdService;
import com.amway.qy.exchanage.req.ReqExchangeUserIdToOpenId;
import com.amway.qy.exchanage.resp.RespExchangeIdResult;
import com.amway.qy.util.common.QyHttpClientUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

public class QyExchangeIdServiceImpl implements QyExchangeIdService {

	private static final Logger logger = LoggerFactory.getLogger(QyExchangeIdServiceImpl.class);
	
	private QyAccessTokenService accessTokenManager;
	
	// Construct here
	public QyExchangeIdServiceImpl(QyAccessTokenService accessTokenManager) {
		this.accessTokenManager = accessTokenManager;
	}
	
	@Override
	public QyAccessTokenService getQyAccessTokenService() {
		return this.accessTokenManager;
	}

	@Override
	public void setQyAccessTokenService(QyAccessTokenService tokenService) {
		this.accessTokenManager = tokenService;
	}

	@Override
	public String convertToOpenIdInRaw(ReqExchangeUserIdToOpenId req) {
		logger.debug("convertToOpenIdInRaw->"+req);
		List<NameValuePair> paramsMap = new ArrayList<NameValuePair>();
		paramsMap.add(new BasicNameValuePair("access_token", accessTokenManager.getAccessToken()));
		return QyHttpClientUtils.httpsPostJson(QyWechatUrls.USERID2OPENID, paramsMap, new Gson().toJson(req));
	}

	@Override
	public RespExchangeIdResult convertToOpenId(ReqExchangeUserIdToOpenId req) {
	
		return new Gson().fromJson(convertToOpenIdInRaw(req), RespExchangeIdResult.class);
	}

	@Override
	public String convertToUserIdInRaw(String opendId) {
		logger.debug("convertToUserIdInRaw->"+opendId);
		
		JsonObject json = new JsonObject();
		json.addProperty("openid", opendId);
		List<NameValuePair> paramsMap = new ArrayList<NameValuePair>();
		paramsMap.add(new BasicNameValuePair("access_token", accessTokenManager.getAccessToken()));
		return QyHttpClientUtils.httpsPostJson(QyWechatUrls.USERID2OPENID, paramsMap, new Gson().toJson(json));
	}

	@Override
	public RespExchangeIdResult convertToUserId(String opendId) {
		return new Gson().fromJson(convertToUserIdInRaw(opendId), RespExchangeIdResult.class);
	}

}
